package com.amox.uitest.kit;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import android.util.Log;

/**
 * @description: Logging tool
 */
public class LogKit {

	Log log;
	/**
	 * Set the level of log
	 * 
	 * @param log
	 * @param level
	 */
	public static void setLogLevel(Logger log, Level level) {
		log.setLevel(level);
	}

	public static void printLog(String pattern, Object... arguments) {
		System.out.println(getPrefix() + " ------- " + StrKit.me().format(pattern, arguments) + " ------- " + getSuffix());
	}
	
	public static void printLog(String msg) {
		System.out.println(getPrefix() + " ------- " + msg + " ------- " + getSuffix());
	}
	
	public static void info(String msg){
		LogFactory.getGlobalLog().info(getPrefix()+"[INFO] "+msg+" - "+getSuffix());
	}

	public static void warn(String msg){
		LogFactory.getGlobalLog().warning(getPrefix()+"[WARN] "+msg+" - "+getSuffix());
	}
	public static void error(String msg){
		LogFactory.getGlobalLog().warning(getPrefix()+"[ERROR] "+msg+" - "+getSuffix());
	}

	public static void log(Level level, String msg){
//		LogFactory.getGlobalLog().log(level, getPrefix()+"["+level.getName()+" ]"+msg+" - "+getSuffix());
	}


	public static void printError(Exception e){
		StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw =  new PrintWriter(sw);
            // Output the failed stack information to the printWriter
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        String msg="[ERROR]"+sw.toString()+" - "+getSuffix();
    	// Output to control to → Pass to apk
		System.out.println(msg);
		// Output to text
//		LogFactory.getGlobalLog().info(msg);
		
	}

	private static String getPrefix(){
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	}
	
	private static String getSuffix(){
		StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[4];
		String className = stackTraceElement.getClassName();
		String methodName = stackTraceElement.getMethodName();
		int methodLine = stackTraceElement.getLineNumber();
		String format = "[%s.%s(L:%d)]";
		return String.format(format, className, methodName, methodLine);
	}

}
